﻿using System.Collections.ObjectModel;
using System.Text.Json.Serialization;

namespace TimeSpan.Models;

public partial class TaskRecordsConfig : ObservableObject {

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(Level))]
    [NotifyPropertyChangedFor(nameof(CurrentExp))]
    [NotifyPropertyChangedFor(nameof(LevelExp))]
    [NotifyPropertyChangedFor(nameof(TotalHours))]
    [NotifyPropertyChangedFor(nameof(TotalMinutes))]
    [NotifyPropertyChangedFor(nameof(TotalTimes))]
    private ObservableCollection<TaskRecord> taskRecords = [];

    [JsonIgnore]
    public int Level { get; set; }

    [JsonIgnore]
    public int CurrentExp { get; set; }

    [JsonIgnore]
    public int LevelExp { get; set; }

    [JsonIgnore]
    public int TotalHours { get; set; }

    [JsonIgnore]
    public int TotalMinutes { get; set; }   

    [JsonIgnore]
    public int TotalTimes { get; set; }

    partial void OnTaskRecordsChanged(ObservableCollection<TaskRecord> value) {
        var totalDuration = System.TimeSpan.FromMinutes(TaskRecords.Sum(x => x.TotalDuartion));
        TotalHours = totalDuration.Hours;
        TotalMinutes = totalDuration.Minutes;
        TotalTimes = TaskRecords.Count();
        // 补全此方法

        // 总经验值为 totalDuration 的总分钟数
        var totalExp = (int)totalDuration.TotalMinutes;

        // 定义每个等级阶段升级所需经验
        var expPerLevelRange = new int[] { 100, 150, 200, 250, 300, 350 };

        // 定义各等级阶段的上限
        var levelRanges = new int[] { 15, 30, 45, 60, 75, 99 };

        // 初始化当前等级和当前经验
        var currentLevel = 0;
        var currentExp = totalExp;

        // 通过循环确定当前的等级和当前等级的经验
        for (int i = 0; i < levelRanges.Length; i++) {
            // 计算当前级别范围内的总经验
            int rangeExp = expPerLevelRange[i] * (levelRanges[i] - (i == 0 ? 0 : levelRanges[i - 1]));

            if (currentExp >= rangeExp) {
                // 如果当前经验大于等于当前范围内的总经验, 进入下一等级范围
                currentExp -= rangeExp;
                currentLevel = levelRanges[i];
            } else {
                // 否则, 在当前范围内计算等级
                currentLevel += currentExp / expPerLevelRange[i];
                currentExp = currentExp % expPerLevelRange[i];
                break;
            }
        }

        // 更新属性
        this.Level = currentLevel;
        this.CurrentExp = currentExp;

        // 确定下一级所需要的经验
        var nextLevelIndex = currentLevel < 15 ? 0
                            : currentLevel < 30 ? 1
                            : currentLevel < 45 ? 2
                            : currentLevel < 60 ? 3
                            : currentLevel < 75 ? 4
                            : 5;

        // 计算当前等级总经验
        this.LevelExp = expPerLevelRange[nextLevelIndex];
    }

}